package com.example.rule.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.rule.common.enums.OperatorEnum;
import com.example.rule.common.exception.ClientException;
import com.example.rule.entity.dto.ConditionSaveDTO;
import com.example.rule.entity.po.ConditionPO;
import com.example.rule.mapper.ConditionMapper;
import com.example.rule.service.ConditionService;
import com.example.rule.toolkit.ExpressionUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Slf4j
@Service
public class ConditionServiceImpl extends ServiceImpl<ConditionMapper, ConditionPO> implements ConditionService {

    private final ConditionMapper conditionMapper;

    @Override
    public void save(ConditionSaveDTO params) {
        // 参数校验
        if (params == null) {
            throw new ClientException("请求参数不能为空");
        }

        if (StrUtil.isBlank(params.getOperator())) {
            throw new ClientException("操作符不能为空");
        }

        if (params.getDataValue() == null) {
            throw new ClientException("数据值不能为空");
        }

        // 校验操作符是否合法（调用 OperatorEnum 获取 symbol）
        try {
            OperatorEnum.getSymbolByDescription(params.getOperator());
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("不支持的操作符: " + params.getOperator());
        }

        String expression = ExpressionUtils.buildExpression(params.getOperator(), params.getDataValue());
        log.info("condition expression: {}", expression);
        ConditionPO po = ConditionPO.builder().expression(expression).build();
        conditionMapper.insert(po);

    }

    @Override
    public List<ConditionPO> list(Integer num) {

        if (num == null || num <= 0) {
            return Collections.emptyList();
        }

        // 使用 lambda 查询，拼接原生 SQL 片段
        return conditionMapper.selectList(new QueryWrapper<ConditionPO>()
                .last("ORDER BY RAND() LIMIT " + num));
    }
}
